package com.penjin.android.activity.kaoqin;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.TextView;

import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.formatter.PercentFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;
import com.penjin.android.R;
import com.penjin.android.constants.HttpConstants;
import com.penjin.android.domain.PenjinCompany;
import com.penjin.android.domain.PenjinDate;
import com.penjin.android.domain.PenjinStaff;
import com.penjin.android.domain.PenjinUser;
import com.penjin.android.http.HttpService;
import com.penjin.android.service.UserService;
import com.penjin.android.utils.HttpUtil;
import com.penjin.android.utils.ToastHelper;
import com.penjin.android.view.CustomProgressDialog;
import com.penjin.android.view.TitleBarView;
import com.penjin.android.widget.calendar.PenjinCalendar;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by Administrator on 2016/4/19.
 * 迟到饼图
 */
public class LateChartActivity extends Activity implements View.OnClickListener, OnChartValueSelectedListener {

    PenjinUser penjinUser;
    PenjinCompany penjinCompany;
    PenjinStaff penjinStaff;

    TitleBarView titleBarView;
    CustomProgressDialog progressDialog;

    HttpService httpService;
    TextHttpResponseHandler handler;

    PieChart pieChart;
    PenjinDate nowDate;
    PenjinDate pickDate;

    List<DepartmentLateBean> dataList = new ArrayList<>();
    TextView lateCounts;
    TextView ymText;
    View preview;
    View next;

    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                setChartData(dataList);
            }
        }
    };

    boolean isLoading = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_activity_latechart);
        initData(savedInstanceState);
        initView();
        initHttp();
    }

    private void initData(Bundle savedIntance) {
        UserService userService = UserService.getInstance(getApplicationContext());
        penjinUser = userService.getCurrentUser();
        if (penjinUser == null) {
            finish();
            ToastHelper.showNotLogin(getApplicationContext());
        } else {
            if (penjinUser.isInCompany()) {
                penjinCompany = userService.getCurrentCompany();
                penjinStaff = userService.getCurrentStaff();
            } else {
                finish();
                ToastHelper.showNotBindCompany(getApplicationContext());
            }
        }
        nowDate = new PenjinDate(new Date());
        pickDate = new PenjinDate(new Date());
    }

    private void initView() {
        lateCounts = (TextView) findViewById(R.id.lateCounts);
        ymText = (TextView) findViewById(R.id.pickDate);
        preview = findViewById(R.id.preview);
        next = findViewById(R.id.next);
        preview.setOnClickListener(this);
        next.setOnClickListener(this);
        pieChart = (PieChart) findViewById(R.id.pieChart);
        titleBarView = (TitleBarView) findViewById(R.id.titleBarView);
        titleBarView.setTitleBarListener(new TitleBarView.TitleBarListener() {


            @Override
            public void left(View view) {
                finish();
            }

            @Override
            public void center(View view) {

            }

            @Override
            public void right(View view) {

            }
        });
        progressDialog = CustomProgressDialog.createDialog(this);
        progressDialog.setMessage("请稍后...");
        initChart();
    }

    @Override
    protected void onResume() {
        super.onResume();
        launchRequest();
    }

    private void initChart() {
        pieChart.setUsePercentValues(true);
        pieChart.setDescription("");
        pieChart.setExtraOffsets(5, 10, 5, 5);

        pieChart.setDragDecelerationFrictionCoef(0.95f);

        //pieChart.setCenterText("部门迟到分布");
        pieChart.setNoDataText("无迟到人员");
        pieChart.setDrawHoleEnabled(true);
        pieChart.setHoleColorTransparent(true);

        pieChart.setTransparentCircleColor(Color.BLACK);
        pieChart.setTransparentCircleAlpha(110);

        pieChart.setHoleRadius(58f);
        pieChart.setTransparentCircleRadius(61f);

        pieChart.setDrawCenterText(true);

        pieChart.setRotationAngle(0);
        pieChart.setRotationEnabled(true);
        pieChart.setHighlightPerTapEnabled(true);
        pieChart.setOnChartValueSelectedListener(this);
    }

    private void setChartData() {
        float range = 100;
        int count = 3;
        float mult = range;

        ArrayList<Entry> yVals1 = new ArrayList<Entry>();

        // IMPORTANT: In a PieChart, no values (Entry) should have the same
        // xIndex (even if from different DataSets), since no values can be
        // drawn above each other.
        for (int i = 0; i < count + 1; i++) {
            yVals1.add(new Entry((float) (Math.random() * mult) + mult / 5, i));
        }

        ArrayList<String> xVals = new ArrayList<String>();

        for (int i = 0; i < count + 1; i++)
            xVals.add("hello" + i);

        PieDataSet dataSet = new PieDataSet(yVals1, "QUE");
        dataSet.setSliceSpace(3f);
        dataSet.setSelectionShift(5f);

        // add a lot of colors

        ArrayList<Integer> colors = new ArrayList<Integer>();

        for (int c : ColorTemplate.VORDIPLOM_COLORS)
            colors.add(c);

        for (int c : ColorTemplate.JOYFUL_COLORS)
            colors.add(c);

        for (int c : ColorTemplate.COLORFUL_COLORS)
            colors.add(c);

        for (int c : ColorTemplate.LIBERTY_COLORS)
            colors.add(c);

        for (int c : ColorTemplate.PASTEL_COLORS)
            colors.add(c);

        colors.add(ColorTemplate.getHoloBlue());

        dataSet.setColors(colors);
        //dataSet.setSelectionShift(0f);

        PieData data = new PieData(xVals, dataSet);
        data.setValueFormatter(new PercentFormatter());
        data.setValueTextSize(11f);
        data.setValueTextColor(Color.WHITE);
        pieChart.setData(data);

        // undo all highlights
        pieChart.highlightValues(null);
        pieChart.setHighlightPerTapEnabled(true);
        pieChart.invalidate();
    }

    private void setChartData(List<DepartmentLateBean> dataList) {
        int count = dataList.size();
        int totalCount = 0;//总迟到次数
        for (DepartmentLateBean bean : dataList) {
            totalCount += bean.lateNumbers;
        }

        ArrayList<Entry> yVals1 = new ArrayList<Entry>();
        float mult = (float) totalCount;

        // IMPORTANT: In a PieChart, no values (Entry) should have the same
        // xIndex (even if from different DataSets), since no values can be
        // drawn above each other.
        for (int i = 0, j = 0; i < count; i++) {
            DepartmentLateBean bean = dataList.get(i);
            if (bean.lateNumbers != 0) {
                Entry entry = new Entry(((float) bean.lateNumbers) / mult, j);
                entry.setData(bean);
                yVals1.add(entry);
                j++;
            }
        }

        ArrayList<String> xVals = new ArrayList<String>();

        for (int i = 0; i < count; i++) {
            DepartmentLateBean bean = dataList.get(i);
            if (bean.lateNumbers != 0) {
                xVals.add(dataList.get(i).department);
            }
        }


        PieDataSet dataSet = new PieDataSet(yVals1, "");
        dataSet.setSliceSpace(3f);
        dataSet.setSelectionShift(5f);

        // add a lot of colors

        ArrayList<Integer> colors = new ArrayList<Integer>();

        for (int c : ColorTemplate.VORDIPLOM_COLORS)
            colors.add(c);

        for (int c : ColorTemplate.JOYFUL_COLORS)
            colors.add(c);

        for (int c : ColorTemplate.COLORFUL_COLORS)
            colors.add(c);

        for (int c : ColorTemplate.LIBERTY_COLORS)
            colors.add(c);

        for (int c : ColorTemplate.PASTEL_COLORS)
            colors.add(c);

        colors.add(ColorTemplate.getHoloBlue());

        dataSet.setColors(colors);
        //dataSet.setSelectionShift(0f);

        PieData data = new PieData(xVals, dataSet);
        data.setValueFormatter(new PercentFormatter());
        data.setValueTextSize(11f);
        data.setValueTextColor(Color.BLACK);
        pieChart.setData(data);
        // undo all highlights
        pieChart.highlightValues(null);
        pieChart.invalidate();
        lateCounts.setText("迟到总人数:" + totalCount);
        int year = pickDate.year;
        int month = pickDate.month;
        ymText.setText(year + "年" + month + "月");
        isLoading = false;
    }

    private void initHttp() {
        httpService = HttpService.getInstance(getApplicationContext());
        handler = new TextHttpResponseHandler() {
            @Override
            public void onFailure(int i, Header[] headers, String s, Throwable throwable) {
                isLoading = false;
                progressDialog.dismiss();
                if (s != null) {
                    System.out.println(s);
                }
                ToastHelper.showServerError(getApplicationContext());
            }

            @Override
            public void onSuccess(int i, Header[] headers, String s) {
                progressDialog.dismiss();
                System.out.println(s);
                try {
                    JSONObject jsonObject = new JSONObject(s);
                    boolean result = jsonObject.getBoolean("result");
                    if (result) {
                        JSONArray jsonArray = jsonObject.getJSONArray("data");
                        dataList.clear();
                        for (int j = 0; j < jsonArray.length(); j++) {
                            DepartmentLateBean bean = new DepartmentLateBean();
                            JSONObject object = jsonArray.getJSONObject(j);
                            bean.department = object.getString("department");
                            bean.lateNumbers = object.getInt("lateNumber");
                            dataList.add(bean);
                        }
                        mHandler.sendEmptyMessage(1);
                    } else {
                        isLoading = false;
                        ToastHelper.showMessage("请求出错!", getApplicationContext());
                    }
                } catch (Exception e) {
                    isLoading = false;
                    e.printStackTrace();
                    ToastHelper.showMessage("服务器请求出错！", getApplicationContext());
                }
            }
        };
    }

    private void launchRequest() {
        isLoading = true;
        RequestParams requestParams = new RequestParams();
        requestParams.put("companyId", penjinCompany.getCompanyId());
        requestParams.put("userName", penjinUser.getPhone());
        requestParams.put("year", pickDate.year);
        requestParams.put("month", pickDate.month);
        progressDialog.show();
        try {
            httpService.postRequest(this, HttpConstants.HOST + HttpConstants.KaoqinDepartmentMonth, requestParams, handler);
        } catch (Exception e) {
            e.printStackTrace();
            ToastHelper.showDNSError(getApplicationContext());
            progressDialog.dismiss();
            isLoading = false;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.preview:
                if (!isLoading) {
                    if (HttpUtil.isNetworkAvailable(this)) {
                        pickDate = PenjinDate.getPreMonth(pickDate);
                        launchRequest();
                    } else {
                        ToastHelper.showNoNetwork(getApplicationContext());
                    }
                }

                break;
            case R.id.next:
                if (!isLoading) {
                    if (HttpUtil.isNetworkAvailable(this)) {
                        if (!pickDate.isSameMonth(nowDate)) {
                            pickDate = PenjinDate.getNextMonth(pickDate);
                            launchRequest();
                        }
                    } else {
                        ToastHelper.showNoNetwork(getApplicationContext());
                    }
                }
                break;
        }
    }

    @Override
    public void onValueSelected(Entry e, int dataSetIndex, Highlight h) {
        System.out.println("chartValueSelected");
        DepartmentLateBean bean = (DepartmentLateBean) e.getData();
        ToastHelper.showMessage(bean.department + "缺勤人数:" + bean.lateNumbers, getApplicationContext());
    }

    @Override
    public void onNothingSelected() {

    }
}
